/* 路由配置文件*/
// 引入
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "@/router/router";
import store from "@/store";
Vue.use(VueRouter); //使用路由

// 重写push || replace 方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      () => {},
      () => {}
    );
  }
};

let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { y: 0 };
  },
});

//配置全局前置路由守卫
router.beforeEach(async (to, from, next) => {
  /**
   * @to 即将跳转的路由
   * @from 当前导航正要离开的路由
   * @next 放行函数
   */
  // 获取用户名字来标识登录状态
  // 若仓库中用户名字是能获取的（接口已经返回数据给仓库）说明已经登录成功
  await store.dispatch("user/getUserInfo")
  let userName = store.state.user.user.name;
  if (userName) {
    // 登录状态
    if (to.path == "/login" || to.path == "/register") {
      //处于登录状态不能跳转至登录页面，重新返回当前页面
      next(from.path);
      console.log("Login路由被拦截");
    } else {
      //跳转至除Login以外的路由
        // 没有用户信息的话获取获取用户信息
            // 放行
            next();        
        console.log(2);
    }
  } else {
    console.log("游客状态");
    let toPath = to.path;
    if(toPath == "detail" || toPath == "shopcart"){
      alert('请先登录！');
      next("/login");
    }
    next();
  }
});



export default router;
